package com.song.interceptor;

import com.song.po.Permission;
import com.song.po.User;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.List;

public class LoginInterceptor implements HandlerInterceptor {
   //进入Controller之间进行验证
   //这个方法有返回值，如果为true，可以进入Controller
   //因此，一般我们需要验证的一些内容都放入到preHandle方法中
   public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
//      System.out.println("==========LoginInterceptor.preHandle==========");
      String uri = request.getRequestURI();

      boolean isRight = false;
      if(uri.indexOf("back") != -1){
         return true;
      }
      if(uri.indexOf("query") != -1){
         return true;
      }
      if(uri.indexOf("loginUser") != -1){
         return true;
      }
      else {
         HttpSession session = request.getSession();
         Object obj = session.getAttribute("loginUser");
         if (obj != null) {
            User user = (User) obj;
            List<Permission> permissions = user.getPermissionList();
            for (Permission p : permissions) {
               if (p.getPermissionUrl().equalsIgnoreCase(uri)) {
                  isRight = true;
                  break;
               }
            }
            if (isRight) {
               return true;
            } else {
               response.sendRedirect("/springDormitory/login.jsp");
            }

         } else {
            response.sendRedirect("/springDormitory/login.jsp");
         }
         return true;
      }
   }

   //进入到Controller中可以执行的方法
   //一般在这个方法中我们可以记录日志
   //或者做一些内容的过滤
   public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
//      System.out.println("==========LoginInterceptor.postHandle==========");
//      System.out.println("handler = " + handler);
//
//      System.out.println(modelAndView.getModel().get("loginUser"));
//
//      System.out.println(modelAndView.getViewName());

   }

   //执行完jsp之后，执行afterCompletion
   //一般这里面就记录日志或者处理异常
   public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
//      System.out.println("==========LoginInterceptor.afterCompletion==========");
   }
}